package service

import (
	"errors"
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/repository"
	"log"

	"gorm.io/gorm"
)

// QuickReplyService 快捷回复服务接口
type QuickReplyService interface {
	CreateQuickReply(staffID uint, req *model.CreateQuickReplyReq) (*model.ChatQuickReply, error)
	GetQuickReply(id uint) (*model.ChatQuickReply, error)
	GetQuickReplyList(staffID uint, req *model.QuickReplyListReq) (*model.QuickReplyListResp, error)
	UpdateQuickReply(id, staffID uint, req *model.UpdateQuickReplyReq) error
	DeleteQuickReply(id, staffID uint) error
}

// quickReplyService 快捷回复服务实现
type quickReplyService struct {
	repo *repository.QuickReplyRepository
}

// NewQuickReplyService 创建快捷回复服务
func NewQuickReplyService(repo *repository.QuickReplyRepository) QuickReplyService {
	return &quickReplyService{
		repo: repo,
	}
}

// CreateQuickReply 创建快捷回复
func (s *quickReplyService) CreateQuickReply(staffID uint, req *model.CreateQuickReplyReq) (*model.ChatQuickReply, error) {
	reply := &model.ChatQuickReply{
		StaffID:   staffID,
		Title:     req.Title,
		Content:   req.Content,
		Category:  req.Category,
		SortOrder: req.SortOrder,
	}

	// 如果是全局话术，设置 StaffID 为 0
	if req.IsGlobal {
		reply.StaffID = 0
		// TODO: 可以添加权限验证，只有管理员可以创建全局话术
	}

	if err := s.repo.Create(reply); err != nil {
		return nil, err
	}

	log.Printf("[快捷回复] 客服 %d 创建了快捷回复: %s", staffID, reply.Title)
	return reply, nil
}

// GetQuickReply 获取快捷回复详情
func (s *quickReplyService) GetQuickReply(id uint) (*model.ChatQuickReply, error) {
	reply, err := s.repo.GetByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("快捷回复不存在")
		}
		return nil, err
	}
	return reply, nil
}

// GetQuickReplyList 获取快捷回复列表
func (s *quickReplyService) GetQuickReplyList(staffID uint, req *model.QuickReplyListReq) (*model.QuickReplyListResp, error) {
	// 参数验证
	if req.Page < 1 {
		req.Page = 1
	}
	if req.PageSize < 1 || req.PageSize > 100 {
		req.PageSize = 20
	}

	replies, total, err := s.repo.GetList(staffID, req.Category, req.IsGlobal, req.Page, req.PageSize)
	if err != nil {
		return nil, err
	}

	return &model.QuickReplyListResp{
		List:     replies,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, nil
}

// UpdateQuickReply 更新快捷回复
func (s *quickReplyService) UpdateQuickReply(id, staffID uint, req *model.UpdateQuickReplyReq) error {
	// 检查快捷回复是否存在
	reply, err := s.repo.GetByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("快捷回复不存在")
		}
		return err
	}

	// 检查权限：只能修改自己的快捷回复
	// 全局话术（staff_id=0）只有管理员可以修改（此处简化，不做管理员验证）
	if reply.StaffID != staffID && reply.StaffID != 0 {
		return errors.New("无权修改此快捷回复")
	}

	// 构建更新字段
	updates := make(map[string]interface{})
	if req.Title != "" {
		updates["title"] = req.Title
	}
	if req.Content != "" {
		updates["content"] = req.Content
	}
	if req.Category != "" {
		updates["category"] = req.Category
	}
	if req.SortOrder != nil {
		updates["sort_order"] = *req.SortOrder
	}

	if len(updates) == 0 {
		return errors.New("没有需要更新的字段")
	}

	if err := s.repo.Update(id, updates); err != nil {
		return err
	}

	log.Printf("[快捷回复] 客服 %d 更新了快捷回复 %d", staffID, id)
	return nil
}

// DeleteQuickReply 删除快捷回复
func (s *quickReplyService) DeleteQuickReply(id, staffID uint) error {
	// 检查快捷回复是否存在
	reply, err := s.repo.GetByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("快捷回复不存在")
		}
		return err
	}

	// 检查权限：只能删除自己的快捷回复
	if reply.StaffID != staffID && reply.StaffID != 0 {
		return errors.New("无权删除此快捷回复")
	}

	if err := s.repo.Delete(id); err != nil {
		return err
	}

	log.Printf("[快捷回复] 客服 %d 删除了快捷回复 %d", staffID, id)
	return nil
}

